<template>
	<view class="nearby-pay" :style="[AppSkinVar]">
		<e-loading-page :loading="loading">
			<template #icon>
				<loader></loader>
			</template>
		</e-loading-page>
		<view class="e-flex e-p-t-24 e-p-b-24 e-p-l-30">
			<image src="/pages/systemPay/static/nearby/icon1.png" class="img-28 e-m-r-14"></image>
			<text>{{ storeAddTxt }}</text>
		</view>
		<view class="nearby-pay__input bg-white">
			<view class="e-m-b-40 e-font-30">{{ $t('nearby.订单金额') }} ({{ $unitEn }})</view>
			<view class="e-flex">
				<text class="e-font-50 e-p-r-20">{{ $unitEn }}</text>
				<input class="e-font-30 e-flex-1" type="digit" v-model="payMoney" @blur="initPaymentPre" :placeholder="$t('nearby.payTxt')" />
			</view>
			<view class="e-p-t-30 e-flex e-flex-between">
				<text class="c-secondary e-font-24">可用积分</text>
				<view>
					<text class="c-secondary e-font-24 e-p-l-20" v-for="(item, index) in deductionList" :key="item.strategy">{{ item.name }}：{{ item.accountMoney }}</text>
				</view>
			</view>
		</view>
		
		<view class="" v-show="payMoney">
			<view class="e-flex e-m-t-20 e-p-t-24 e-p-b-24 e-p-l-30 bg-white">
				{{ $t('nearby.deduction') }}
			</view>
			<view class="bg-white">
				<view class="nearby-pay__mode " v-for="item in deductionList" :key="item.strategy">
					<view class="nearby-pay__mode__mask" @tap="handleTapDeductionItem(item)"></view>
					<view class="e-flex e-p-b-20">
						<view class="e-m-r-10">
							<load-image size="32rpx" :src="item.icon"></load-image>
						</view>
						<text class="e-font-24 c-regular">{{ item.name }}</text>
						<text class="e-font-24 c-regular">积分抵扣</text>
					</view>
					<e-line color="#E6E6E6"></e-line>
					<view class="e-flex e-flex-between e-p-t-20">
						<text class="fw-600">{{ $unitEn }}{{ item.payMoney }} + {{ item.deductMoney }}{{ item.name }}</text>
						<view class="e-flex">
							<radio :disabled="!item.deductMoney" :color="AppSkin.primary" :value="`${item.strategy}`" :checked="item.check" @tap.stop="handleTapDeductionItem(item)" />
						</view>
					</view>
				</view>
				<view class="nearby-pay__mode">
					<view class="nearby-pay__mode__mask" @tap="handleTapDeductionItem(false)"></view>
					<view class="e-flex e-p-b-20">
						<image src="/pages/systemPay/static/nearby/icon.png" class="img-32 e-m-r-10"></image>
						<text class="e-font-24 c-regular e-p-r-10">原价购买</text>
					</view>
					<e-line color="#E6E6E6"></e-line>
					<view class="e-flex e-flex-between e-p-t-20">
						<text class="fw-600">{{ $unitEn }}{{ payMoney }}</text>
						<view class="e-flex">
							<radio :color="AppSkin.primary" value="-1" :checked="hasOriginal"  />
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="nearby-pay__pay bg-white">
			<view class="nearby-pay__pay__preferential">
				<view class="nearby-pay__pay__preferential-box e-flex e-p-l-40" :style="[payInfoStyle]">
					<text class="c-primary e-p-r-10">{{ $t('order.优惠') }} {{ $unitEn }}{{ payMoneyDis }}</text>
					<text class="c-primary">{{ $t('order.抵扣') }} {{ $unitEn }}{{ deductMoney }}</text>
				</view>
			</view>
			<view class="nearby-pay__pay__box e-flex e-flex-between">
				<view class="e-flex">
					<text class="e-font-30">{{ $t('cart.总计') }}：</text>
					<text class="c-primary e-font-36 fw-500">{{ payTotalMoney }}</text>
				</view>
				<view class="nearby-pay__pay__box-btn bg-primary c-white e-flex-xy-center" :class="{ 'is-ok': !payMoney }" @tap="buy">
					{{ $t('nearby.payConfirm') }}
				</view>
			</view>
		</view>
		<pay-popup storeType="2" :payMoney="payTotalMoney" :hiddenStrategys="hiddenStrategys" v-model:show="passwordShow" @close="passwordShow = false" @pay="pay" v-if="isLogin"></pay-popup>
		<card-valid-code-popup :show="cardValidCodePopupShow" :payMoney="payTotalMoney" @cancel="handleCancelCardPay" @confirm="handleCardPay"></card-valid-code-popup>
	</view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { throttle } from '@/common/utils';
import { postStorePay, getNearbyStorePayResult, getNearbyStoreDetail, getStorePaymentPre, getStoreOwnerDetail } from '@/common/request/api';
import type { deductionAccountItem, PurchaseGoodsPayData } from '@/common/request/api';

// import {
// 	reRequest
// } from 'common/utils/utils'
// #ifdef MP-WEIXIN
import { sceneParamsToObj, getWxScene } from '@/common/utils';
// #endif
import { useCurrentInstance } from '@/common/hooks';
import { useUser, useInit } from '@/common/stores';
import { storeToRefs } from 'pinia';
import CardValidCodePopup from '../child/cardValidCodePopup.vue'
import { onLoad, onShow } from '@dcloudio/uni-app';
import { reRequest, usePay } from '../hooks/usePay';
import type { UniGlobalData } from '@/typings/uni';
import { PayType } from '@/env';
import { isNumber } from '@/common/utils';

const ctx = useCurrentInstance();

const userStore = useUser();

const { isLogin } = storeToRefs(userStore);
const { AppSkin } = storeToRefs(useInit());

const { systemPay,checkCardPay,handleCardPay,
		handleCancelCardPay,cardValidCodePopupShow, getH5PayResult } = usePay();

let storeId = '';

const loading = ref(false);

const payMoney = ref('');
const deductionsInfo = ref({
	payMoney: 0,
	payDeductMoney: 0,
	paymentDisMoney: 0
});
const deductionModeId = ref<string[]>([]); //选中的抵扣账户
const paymentDis = ref(0); //买单优惠比例
const deductionType = ref('N'); //Y 可多选账户抵扣，N 只能单选账户抵扣
const deductionMode = ref('N'); //Y 抵扣账户需足额抵扣，N 抵扣账户可不足额抵扣
const deductionList = ref<deductionAccountItem[]>([]); //选中的抵扣账户
const initPaymentPre = () => {
	if (storeId) {
		getStorePaymentPre({
			storeId,
			money: payMoney.value,
			deductionStrategy: deductionModeId.value.join(',')
		}).then((res) => {
			paymentDis.value = res.data.paymentDis;
			deductionMode.value = res.data.deductionMode;
			deductionType.value = res.data.deductionType;
			deductionList.value = res.data.deductions;
			deductionsInfo.value = {
				payMoney: res.data.payMoney, //总计
				payDeductMoney: res.data.payDeductMoney, //买单优惠金额
				paymentDisMoney: res.data.paymentDisMoney //总抵扣
			};
		});
	}
};

const payMoneyDis = computed(() => deductionsInfo.value?.paymentDisMoney || 0);
const deductMoney = computed(() => deductionsInfo.value?.payDeductMoney || 0);

const payInfoStyle = computed(() => {
	return {
		background: AppSkin.value.primary.replace('1)', '0.1)')
	};
});
const payTotalMoney = computed(() => isNumber(deductionsInfo.value?.payMoney) ? deductionsInfo.value?.payMoney : payMoney.value || 0);

const storeAddTxt = ref('');
const hiddenStrategys = ref<string[]>([])
const init = () => {
	getNearbyStoreDetail(storeId).then((res) => {
		storeAddTxt.value = res.data.name;
		hiddenStrategys.value = res.data?.fee >= 20 ? [] :['xiaofeiquan'] 
	});
	initPaymentPre();
};
const hasOriginal = ref(false)
const handleTapDeductionItem = (items: deductionAccountItem | boolean) => {
	if (!payMoney.value) {
		ctx.$toastApp(ctx.$t('nearby.buyErr'));
		return;
	}
	
	if (items) {
		if(items.deductMoney){
			hasOriginal.value = false
			if(deductionType.value === 'N'){
				deductionModeId.value = [items.strategy]
			}else{
				if (deductionModeId.value.includes(items.strategy)) {
					deductionModeId.value.splice(
						deductionModeId.value.findIndex((item) => item === items.strategy),
						1
					);
				} else {
					deductionModeId.value.push(items.strategy);
				}
			}
			
		}
		
	} else {
		hasOriginal.value = true;
		deductionModeId.value = [];
	}
	
	initPaymentPre();
};
const passwordShow = ref(false);
const buy = () => {
	if (!payMoney.value) {
		ctx.$toastApp(ctx.$t('nearby.buyErr'));
		return;
	}

	if (!isLogin.value) {
		ctx.$goLogin({
			isShowModal: true
		});
	}
	passwordShow.value = true;
};
// 支付
const pay = throttle(async function (payId: number, payword: string | undefined = undefined, payType: PayType, payName: string,payisDefault:string,bankId?:number) {
	let data = {
		payId,
		money: payMoney.value,
		deductionStrategy: deductionModeId.value.join(','),
		fromType: getApp<UniGlobalData>().globalData?.payFromType,
		payword,
		bankId
	};
	uni.setStorageSync('nearbyStorePayName', payName);
	if(!bankId&&checkCardPay(payType,(cardId:number) => {
		pay(payId,payword, payType,payName,payisDefault,cardId)
	})){
		return 
	}
	uni.hideLoading();
	const res = await postStorePay(storeId, data);

	await systemPay({
		payType,
		resolveData: res,
		payParams: res.data,
		api: getNearbyStorePayResult,
		storageKey: 'nearbyStorePayOrderId',
		errorUrl: (msg: string) => `nearby/order/error?name=${storeAddTxt.value}&mode=${payName}&msg=${msg}`,
		orderIdKey: 'paycode',
		payMoney:payTotalMoney.value,
		callBack: (resultRes: PurchaseGoodsPayData) => {
			payMoney.value = '';
			uni.removeStorageSync('nearbyStorePayName');
			if (payType === 'SYS') {
				uni.showLoading({
					title: 'loading...'
				});
				setTimeout(() => {
					// 系统支付,需查询支付的金额
					reRequest(getNearbyStorePayResult, 5, res.paycode)
						.then((_resultRes) => {
							ctx.$goRedirectTo('/pages/nearby/order/success', {
								name: storeAddTxt.value,
								mode: payName,
								money: _resultRes.data.payMoney,
								id: res.paycode
							});
						})
						.finally(() => {
							uni.hideLoading();
						});
				},1500)
			} else {
				ctx.$goRedirectTo('/pages/nearby/order/success', {
					name: storeAddTxt.value,
					mode: payName,
					money: resultRes.data.payMoney,
					id: res.paycode
				});
			}
		}
	});
}, 1500);

onLoad(async (opt) => {
	// #ifdef MP-WEIXIN
	if (opt?.id) {
		storeId = opt.id;
	} else {
		if (opt?.q) {
			const q = decodeURIComponent(opt.q);
			const id = getWxScene('id', q);
			if (id) {
				storeId = id;
			}
		} else if (opt?.scene) {
			let query = sceneParamsToObj(opt.scene);
			if (query.id) {
				storeId = query.id;
			}
		}
	}

	// #endif

	// #ifndef MP-WEIXIN
	storeId = opt?.id || '';
	// #ifdef MP-ALIPAY
	let _id = uni.getStorageSync('ali-store-id');
	if (_id) {
		storeId = _id;
	}
	// #endif

	// #endif

	getStoreOwnerDetail({
		storeId
	}).then((res) => {
		uni.setStorageSync('userSalt', res.data.storeSalt);
	});

	init();
	if (!isLogin.value) {
		await userStore.getUserInfo();
	}
});

onShow(async () => {
	isLogin.value && initPaymentPre();
	getH5PayResult('nearby/order/success', 'nearbyStorePayOrderId', getNearbyStorePayResult).then(async ({ res, orderId }) => {
		if (!storeAddTxt.value) {
			const res = await getNearbyStoreDetail(storeId);
			if (res.code === 200) {
				storeAddTxt.value = res.data.name;
			}
		}
		const payName = uni.getStorageSync('nearbyStorePayName');
		uni.removeStorageSync('nearbyStorePayName');
		uni.redirectTo({
			url: `nearby/order/success?name=${storeAddTxt.value}&mode=${payName}&money=${res.payMoney}&id=${orderId}`
		});
	});
});
</script>
<style>
page {
	background: #f3f3f3;
}
</style>
<style lang="scss" scoped>
.nearby-pay {
	padding-bottom: 196rpx;

	&__input {
		padding: 40rpx 30rpx;
	}

	&__mode {
		padding: 20rpx 32rpx;
		position: relative;

		&__mask {
			position: absolute;
			left: 0;
			top: 0;
			right: 0;
			bottom: 0;
			z-index: 1;
		}
	}

	&__pay {
		position: fixed;
		height: 176rpx;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1;

		&__preferential {
			height: 64rpx;

			&-box {
				height: 64rpx;
			}
		}

		&__box {
			height: 112rpx;
			padding: 0 40rpx;

			&-btn {
				border-radius: 46rpx;
				padding: 0 56rpx;
				height: 80rpx;
			}
		}
	}
}

.font-50 {
	font-size: 50rpx;
}
</style>
